/*
 *   SlimPlayer Copyright (c) 2006 Koelec
 *
 *   This file is part of SlimPlayer plugin for SageTv.
 *
 *   Slimplayer is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   Slimplayer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with SoftSqueeze; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

package nl.cmkprojects.sage.web;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.webharvest.definition.ScraperConfiguration;
import org.webharvest.runtime.Scraper;
import org.webharvest.runtime.variables.ListVariable;
import org.webharvest.runtime.variables.Variable;

/**
 * @author Chris
 * 
 *         To change the template for this generated type comment go to Window -
 *         Preferences - Java - Code Generation - Code and Comments
 */
public class WebHarvestArtistNewsRetriever implements ArtistNewsRetriever {
	public static Logger logger = Logger
			.getLogger(WebHarvestArtistNewsRetriever.class);

	public static void main(String[] args) {
		ArtistNewsRetriever anr;

		anr = new WebHarvestArtistNewsRetriever();
		// air.getInfo("last+shadow+puppets");
		// anr.getNews("average+white+band");
		anr
				.getNewsItem("/duran-duran/news/duran-duran-gets-a-timbaland-update--12174839");
	}

	public String getNewsItem(String newsUri) {
		logger.debug("NewsRetriever(" + newsUri + ")");
		String news = "";
		Scraper scraper = null;
		try {
			ScraperConfiguration config = new ScraperConfiguration(
					"slimplayer/slimplayer-ai-news-item.xml");
			scraper = new Scraper(config, ".");
			scraper.addVariableToContext("newsUri", newsUri);

			if (logger.isDebugEnabled()) {
				scraper.setDebug(true);
			}

			scraper.execute();

			// takes variable created during execution
			Variable newsItemHeadlineVar = (Variable) scraper.getContext().get(
					"newsItemHeadline");
			Variable newsItemSourceVar = (Variable) scraper.getContext().get(
					"newsItemSource");
			Variable newsItemBodyVar = (Variable) scraper.getContext().get(
					"newsItemBody");
			String text = InfoFormatter.formatText(newsItemHeadlineVar
					.toString(), "\n");
			StringBuffer sb = new StringBuffer();
			sb.append(text);
			sb.append("\n");
			text = newsItemSourceVar.toString();
			sb.append(text);
			sb.append("\n \n"); // sagetv text area needs a space on an empty
			// line
			text = InfoFormatter.formatText(newsItemBodyVar.toString(), "\n");
			sb.append(text);
			news = sb.toString();
			logger.debug(news);
		} catch (Exception e) {
			logger.debug("failed to run scraper", e);
		} finally {
			if (scraper != null) {
				scraper.dispose();
			}
		}
		return news;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * nl.cmkprojects.sage.webradio.ArtistInfoRetriever#getInfo(java.lang.String
	 * )
	 */

	public ArtistNews getNews(String artistName) {
		logger.debug("NewsRetriever(" + artistName + ")");
		ArtistNews news = new ArtistNews();
		news.setName(artistName);
		news.setItemRefList(new ArrayList<ArtistNewsRef>());

		Scraper scraper = null;
		try {
			ScraperConfiguration config = new ScraperConfiguration(
					"slimplayer/slimplayer-ai-news.xml");
			scraper = new Scraper(config, ".");
      String searchName = URLEncoder.encode(artistName, "UTF-8");
			scraper.addVariableToContext("artist", searchName);

			if (logger.isDebugEnabled()) {
				scraper.setDebug(true);
			}

			scraper.execute();

			// takes variable created during execution
			List<Object> newsHrefList = getScraperVarList(scraper,
					"newsItemsHref");
			List<Object> newsHeadlinesList = getScraperVarList(scraper,
					"newsItemsTitle");
			List<Object> newsSourceList = getScraperVarList(scraper,
					"newsItemsSource");
			List<Object> newsItemsList = getScraperVarList(scraper,
					"newsItemsTeaser");
			for (int i = 0; i < newsHrefList.size(); i++) {
				ArtistNewsRef anr = new ArtistNewsRef();
				anr.setUrl(newsHrefList.get(i).toString());
				newsHeadlinesList.get(i);
				anr.setHeadline(InfoFormatter.formatText(newsHeadlinesList.get(
						i).toString(), " "));
				anr.setSource(newsSourceList.get(i).toString());
				anr.setText(InfoFormatter.formatText(newsItemsList.get(i)
						.toString(), "\n"));
				news.getItemRefList().add(anr);
			}
			logger.debug(news);
		} catch (Exception e) {
			logger.debug("failed to run scraper", e);
		} finally {
			if (scraper != null) {
				scraper.dispose();
			}
		}
		return news;
	}

	@SuppressWarnings("unchecked")
	private List<Object> getScraperVarList(Scraper scraper, String varName) {
		ListVariable listVar = (ListVariable) scraper.getContext().get(varName);
		if (listVar.isEmpty()) {
			return new ArrayList<Object>();
		}
		return (List<Object>) listVar.toList();
	}
}
